package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.xbatis.core.mybatis.mapper.context.Pager;
import cn.xbatis.core.sql.executor.chain.QueryChain;
import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.CacheUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.dao.SysDictDataDao;
import com.ruoyi.system.domain.bo.SysDictDataBo;
import com.ruoyi.system.domain.vo.SysDictDataVo;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysDictDataServiceImpl implements ISysDictDataService {

    private final SysDictDataMapper baseMapper;
    @Autowired
    private SysDictDataDao sysDictDataDao;

    protected SysDictDataDao getDao() {
        return sysDictDataDao;
    }

    @Override
    public TableDataInfo<SysDictDataVo> selectPageDictDataList(SysDictDataBo dictData, PageQuery pageQuery) {
        Pager<SysDictDataVo> pager = buildQueryWrapper(dictData).returnType(SysDictDataVo.class).paging(Pager.of(pageQuery.getPageNum(), pageQuery.getPageSize()));
        return TableDataInfo.builds(pager);
    }

    private QueryChain<SysDictData> buildQueryWrapper(SysDictDataBo bo) {
        return QueryChain.of(baseMapper)
            .eq(StringUtils.isNotBlank(bo.getDictType()), SysDictData::getDictType, bo.getDictType())
            .like(StringUtils.isNotBlank(bo.getDictLabel()), SysDictData::getDictLabel, bo.getDictLabel())
            .eq(bo.getDictSort() != null, SysDictData::getStatus, bo.getDictSort())
            .orderBy(SysDictData::getDictSort);
    }

    /**
     * 根据条件分页查询字典数据
     *
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictDataVo> selectDictDataList(SysDictDataBo dictData) {
        return buildQueryWrapper(dictData).returnType(SysDictDataVo.class).list();

    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        return QueryChain.of(baseMapper)
            .select(SysDictData::getDictLabel)
            .eq(SysDictData::getDictType, dictType)
            .eq(SysDictData::getDictValue, dictValue).get()
            .getDictLabel();
    }

    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictDataVo selectDictDataById(Long dictCode) {

        return baseMapper.getById(SysDictDataVo.class, dictCode);
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictDataVo data = selectDictDataById(dictCode);
            baseMapper.deleteById(dictCode);
            CacheUtils.evict(CacheNames.SYS_DICT, data.getDictType());
        }
    }

    /**
     * 新增保存字典数据信息
     *
     * @param bo 字典数据信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#bo.dictType")
    @Override
    public int insertDictData(SysDictDataBo bo) {
        SysDictData data = BeanUtil.toBean(bo, SysDictData.class);
        int row = baseMapper.save(data);
        if (row > 0) {
            List<SysDictData> dictDatas = QueryChain.of(baseMapper)
                .eq(SysDictData::getStatus, UserConstants.DICT_NORMAL)
                .eq(SysDictData::getDictType, data.getDictType())
                .orderBy(SysDictData::getDictSort).list();
            RedisUtils.setCacheObject(getCacheKey(data.getDictType()), dictDatas);
        }
        return row;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    String getCacheKey(String configKey) {
        return Constants.SYS_DICT_KEY + configKey;
    }

    /**
     * 修改保存字典数据信息
     *
     * @param bo 字典数据信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#bo.dictType")
    @Override
    public List<SysDictDataVo> updateDictData(SysDictDataBo bo) {
        SysDictData data = BeanUtil.toBean(bo, SysDictData.class);
        int row = baseMapper.update(data, c -> c.eq(SysDictData::getDictCode, data.getDictCode()));
        if (row > 0) {
            List<SysDictDataVo> sysDictDataVos = getDao().selectDictDataByType(data.getDictType());
            return sysDictDataVos;
        }
        throw new ServiceException("操作失败");
    }

}
